#!/bin/bash

# Configuration, Focal Fossa
UB_RELEASE="20.04.4"
UBUNTU_VERSION="20.04.5"
#WORK_DIR="$HOME/ubuntu"
WORK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
ROOTFS_DIR="$WORK_DIR/ubuntu_rootfs_rk3588"
UBUNTU_BASE_URL="https://cdimage.ubuntu.com/ubuntu-base/releases/${UB_RELEASE}/release/ubuntu-base-${UBUNTU_VERSION}-base-arm64.tar.gz"
IMAGE_SIZE="8192" # Size in MB
TIMEZONE="Asia/Hong_Kong"
LOCALE="en_US.UTF-8"
USERNAME="ubuntu"
PASSWORD="123"
INSTALL_DESKTOP=true
DESKTOP_ENV="lubuntu-desktop"
ROOT_LOGIN=false
AUTO_UPGRADE=false
RESIZE_PARTITION="/dev/mmcblk0p6" # Set to empty to disable
LOG_FILE="$WORK_DIR/ubuntu_customization.log"

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function: Log info
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
    #echo "[INFO] $1" >> "$LOG_FILE"
}

# Function: Log warning
log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
    #echo "[WARNING] $1" >> "$LOG_FILE"
}

# Function: Log error
log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
    #echo "[ERROR] $1" >> "$LOG_FILE"
}

# Function to prompt for yes/no confirmation
confirm() {
    read -p "$1 [y/N] " response
    case "$response" in
        [yY][eE][sS]|[yY]) 
            true
            ;;
        *)
            false
            ;;
    esac
}

# Function to retry a command
retry() {
    local retries=$1
    shift
    local count=0
    until "$@"; do
        exit=$?
        count=$((count + 1))
        if [ $count -lt $retries ]; then
            log_warning "Command failed. Attempt $count/$retries:"
            sleep 5
        else
            log_error "The command has failed after $retries attempts."
            return $exit
        fi
    done
    return 0
}

# Check if script is run as root
check_root() {
    if [ "$(id -u)" != "0" ]; then
        log_error "This script must be run as root"
        exit 1
    fi
}

# Function to check if we're running inside Docker
in_docker() {
    [ -f /.dockerenv ] || grep -Eq '(lxc|docker)' /proc/1/cgroup
}
